import {
    getStatusByFlow,
} from '../model/getdata';
import {
    updateFormat,
} from '../model/updateFormat';
import {
    updateFormat_mc_cancel,
    updateFormat_mc,
    isMerged,
} from '../model/mergeCell'
import {
    luckysheetrefreshgrid,
} from '../view/refresh';
import editor from '../model/editor';
import {
    createButtonMenu,
    changeMenuButtonDom,
} from '../view/menuButtonDom';
import {
    clearmenuelement,
} from '../view/cleargridelement';
import {
    replaceHtml,
    mouseclickposition,
} from '../utils/util';
import {
    fontSizeItems,
    mergeItems,
    alignItems,
    valignItems,
} from '../utils/menuItems';
import {
    dropListMenu,
    iconfontObjects,
    colorList,
    colorItemList,
} from '../utils/constant';
import Store from '../store';

export {
    initialMenuButton,
    menuButtonFocus,
};

function initialMenuButton() {
    $("#luckysheet-icon-font-size").mousedown(function (e) {
        e.stopPropagation();
    }).click(function () {
        let itemdata = fontSizeItems;
        let itemset = createButtonMenu(itemdata);
        let dropListFontSize = dropListMenu;
        let menuHTML = replaceHtml(dropListFontSize, {
            "id": "font-size",
            "item": itemset,
            "subclass": "",
            "sub": ""
        });
        popupMenu($(this), menuHTML, 150, "fs");
    })

    //加粗
    $("#luckysheet-icon-bold").mousedown(function (e) {
        e.stopPropagation();
    }).click(function () {
        buttonClickEvent("bl");
    });

    //斜体
    $("#luckysheet-icon-italic").mousedown(function (e) {
        e.stopPropagation();
    }).click(function () {
        buttonClickEvent("it");
    });

    //删除线
    $("#luckysheet-icon-strikethrough").mousedown(function (e) {
        e.stopPropagation();
    }).click(function () {
        buttonClickEvent("cl");
    });

    //下划线
    $("#luckysheet-icon-underline").mousedown(function (e) {
        e.stopPropagation();
    }).click(function () {
        buttonClickEvent("un");
    });

    //合并单元格
    $("#luckysheet-icon-merge-button").click(function () {
        let d = editor.deepCopyFlowData(Store.flowdata);

        if (isMerged(d)) {
            updateFormat_mc_cancel(d);
        } else {
            updateFormat_mc(d, "mergeAll");
        }
        Store.flowdata = d;
        luckysheetrefreshgrid();
    });


    $("#luckysheet-icon-merge-menu").click(function () {
        let itemdata = mergeItems;
        let itemset = createButtonMenu(itemdata);

        let dropListMergeCell = dropListMenu;
        let menuHTML = replaceHtml(dropListMergeCell, {
            "id": "merge-menu",
            "item": itemset,
            "subclass": "",
            "sub": ""
        });
        popupMenu($(this), menuHTML, 150, "mc");

    });

    //水平对齐
    $("#luckysheet-icon-align").click(function () {
        let itemvalue = $("#luckysheet-icon-align").attr("type");
        if (itemvalue == null) {
            itemvalue = "left";
        }

        let d = editor.deepCopyFlowData(Store.flowdata);
        refreshFormat(d, "ht", itemvalue);
    });

    $("#luckysheet-icon-align-menu").click(function () {
        let itemdata = alignItems;
        let itemset = createButtonMenu(itemdata);
        let dropListAlign = dropListMenu;
        let menuHTML = replaceHtml(dropListAlign, {
            "id": "align-menu",
            "item": itemset,
            "subclass": "",
            "sub": ""
        });
        popupMenu($(this), menuHTML, 120, "ht");

    });

    //垂直对齐
    $("#luckysheet-icon-valign").click(function () {
        let itemvalue = $("#luckysheet-icon-valign").attr("type");
        if (itemvalue == null) {
            itemvalue = "bottom";
        }

        let d = editor.deepCopyFlowData(Store.flowdata);
        refreshFormat(d, "vt", itemvalue);
    });

    $("#luckysheet-icon-valign-menu").click(function () {
        let itemdata = valignItems;
        let itemset = createButtonMenu(itemdata);
        let dropListVAlign = dropListMenu;
        let menuHTML = replaceHtml(dropListVAlign, {
            "id": "valign-menu",
            "item": itemset,
            "subclass": "",
            "sub": ""
        });

        popupMenu($(this), menuHTML, 120, "vt");

    });

    //背景颜色
    $("#luckysheet-icon-cell-color").click(function () {
        let d = editor.deepCopyFlowData(Store.flowdata);
        let color = $(this).attr("color");
        if (color == null) {
            color = "#ffffff";
        }
        refreshFormat(d, "bg", color);
    });

    $("#luckysheet-icon-cell-color-menu").click(function () {
        let menuButtonId = $(this).attr("id") + "-menuButton";
        let $menuButton = $("#" + menuButtonId);

        if ($menuButton.length == 0) {
            let subid = "cell-color-self";
            let item = colorItemList;
            let color = colorList;
            let coloritem = replaceHtml(item, {
                "class": "luckysheet-icon-alternateformat",
                "name": "alternatingColors"
            });
            let menu = replaceHtml(color, {
                "id": menuButtonId,
                "coloritem": coloritem,
                "colorself": subid,
                "sub": "",
                "resetColor": "resetColor"
            });

            $("body").append(menu);
            $menuButton = $("#" + menuButtonId);

            $("#" + menuButtonId).find(".luckysheet-color-selected").spectrum({
                showPalette: true,
                showPaletteOnly: true,
                preferredFormat: "hex",
                clickoutFiresChange: false,
                showInitial: true,
                showInput: true,
                flat: true,
                hideAfterPaletteSelect: true,
                showSelectionPalette: true,
                maxPaletteSize: 8,
                maxSelectionSize: 8,
                color: "#fff",
                cancelText: "cancel",
                chooseText: "confirm",
                togglePaletteMoreText: "customColor",
                togglePaletteLessText: "collapse",
                togglePaletteOnly: true,
                clearText: "clearText",
                noColorSelectedText: "noColorSelectedText",
                palette: [
                    ["#000", "#444", "#666", "#999", "#ccc", "#eee", "#f3f3f3", "#fff"],
                    ["#f00", "#f90", "#ff0", "#0f0", "#0ff", "#00f", "#90f", "#f0f"],
                    ["#f4cccc", "#fce5cd", "#fff2cc", "#d9ead3", "#d0e0e3", "#cfe2f3", "#d9d2e9", "#ead1dc"],
                    ["#ea9999", "#f9cb9c", "#ffe599", "#b6d7a8", "#a2c4c9", "#9fc5e8", "#b4a7d6", "#d5a6bd"],
                    ["#e06666", "#f6b26b", "#ffd966", "#93c47d", "#76a5af", "#6fa8dc", "#8e7cc3", "#c27ba0"],
                    ["#c00", "#e69138", "#f1c232", "#6aa84f", "#45818e", "#3d85c6", "#674ea7", "#a64d79"],
                    ["#900", "#b45f06", "#bf9000", "#38761d", "#134f5c", "#0b5394", "#351c75", "#741b47"],
                    ["#600", "#783f04", "#7f6000", "#274e13", "#0c343d", "#073763", "#20124d", "#4c1130"]
                ],
                change: function (color) {
                    if (color != null) {
                        color = color.toHexString();
                    } else {
                        color = "#fff";
                    }

                    $("#luckysheet-icon-cell-color .text-color-bar").css("background-color", color);
                    $("#luckysheet-icon-cell-color").attr("color", color);
                    let d = editor.deepCopyFlowData(Store.flowdata);
                    refreshFormat(d, "bg", color);

                    $menuButton.hide();
                    $("#" + Store.container).attr("tabindex", 0).focus();
                }
            });

            $menuButton.find(".luckysheet-color-reset").click(function () {
                $menuButton.hide();
                $("#" + Store.container).attr("tabindex", 0).focus();

                let $input = $("#" + menuButtonId).find(".luckysheet-color-selected");
                $input.val("#ffffff");
                $("#luckysheet-icon-cell-color").attr("color", null);
                $input.spectrum("set", "#ffffff");
                $("#luckysheet-icon-cell-color .luckysheet-color-menu-button-indicator").css("border-bottom-color", "#ffffff");

                let d = editor.deepCopyFlowData(Store.flowdata);
                refreshFormat(d, "bg", null);
            });


            $("#" + menuButtonId).find(".luckysheet-color-selected").val("#fff");
        }

        let userlen = $(this).outerWidth();
        let tlen = $menuButton.outerWidth();

        let menuleft = $(this).offset().left;
        if (tlen > userlen && (tlen + menuleft) > $("#" + Store.container).width()) {
            menuleft = menuleft - tlen + userlen;
        }

        let $input = $("#" + menuButtonId).find(".luckysheet-color-selected");
        $input.spectrum("set", $input.val());
        mouseclickposition($menuButton, menuleft, $(this).offset().top + 25, "lefttop");

    });


}

// Private function
function refreshFormat(d, type, foucsStatus) {
    updateFormat(d, type, foucsStatus);
    Store.flowdata = d;
    luckysheetrefreshgrid();
}
function menuButtonFocus(d, r, c) {
    let foucsList = ["bl", "it", "cl", "ff", "ht", "vt", "fs", "tb", "tr", "ct", "un", "mc"];
    for (let i = 0; i < foucsList.length; i++) {
        let attr = foucsList[i];
        let foucsStatus = getStatusByFlow(d, r, c, attr);

        changeMenuButtonDom(attr, foucsStatus);
    }
}

function buttonClickEvent(type) {
    let d = editor.deepCopyFlowData(Store.flowdata);
    let row_index = Store.luckysheet_select_save[0]["row_focus"],
        col_index = Store.luckysheet_select_save[0]["column_focus"];
    let foucsStatus = getStatusByFlow(d, row_index, col_index, type);

    if (foucsStatus == 1) {
        foucsStatus = 0;
    } else {
        foucsStatus = 1;
    }

    refreshFormat(d, type, foucsStatus);
    menuButtonFocus(d, row_index, col_index);
}

function popupMenu(menuClicked, menuHTML, menuWidth, type) {
    clearmenuelement();
    let menuButtonId = $(menuClicked).attr("id") + "-menuButton";
    let $menuButton = $("#" + menuButtonId);

    if ($menuButton.length == 0) {
        $("body").append(menuHTML);
        $menuButton = $("#" + menuButtonId).width(menuWidth);

        $menuButton.find(".luckysheet-cols-menuitem").click(function () {

            $menuButton.hide();
            $("#" + Store.container).attr("tabindex", 0).focus();

            let $t = $(this),
                itemvalue = $t.attr("itemvalue");
            menuClicked.attr("itemvalue", itemvalue);
            focus($menuButton, itemvalue);

            let d = editor.deepCopyFlowData(Store.flowdata);
            if (type == 'mc') {
                if (isMerged(d)) {
                    updateFormat_mc_cancel(d);
                } else {
                    updateFormat_mc(d, itemvalue);
                }
            } else {
                if (type == 'ht') {
                    const iconfontObject = iconfontObjects.align;
                    let $icon = $("#luckysheet-icon-align").attr("type", itemvalue).find(".luckysheet-icon-img-container");
                    // add iconfont
                    $icon.removeAttr("class").addClass("luckysheet-icon-img-container luckysheet-icon-img luckysheet-icon-align-" + itemvalue + iconfontObject[itemvalue]);
                } else if (type == 'fs') {
                    let input = $("#luckysheet-icon-font-size input");
                    input.val(itemvalue);
                }
                updateFormat(d, type, itemvalue);
            }
            Store.flowdata = d;
            luckysheetrefreshgrid();
        });
    }

    let userlen = $(menuClicked).outerWidth();
    let tlen = $menuButton.outerWidth();

    let menuleft = $(menuClicked).offset().left;
    if (tlen > userlen && (tlen + menuleft) > $("#" + Store.container).width()) {
        menuleft = menuleft - tlen + userlen;
    }
    mouseclickposition($menuButton, menuleft, $(menuClicked).offset().top + 25, "lefttop");
}
